<?php

require_once 'StrUtil.php';
require_once 'SearchUtil.php';
require_once WB_LIB_DIR . "/view/StrFormat.php";
/**
 * 消息内容替换
 *
 * @author ericcao
 */
class MessageUtil
{
    /**
     * 这里转义||@形式
     * */
    const REPLACE_PATTERN = "/(#\s*[^#\s]{1}[^#]{0,59}?\s*#)|(\|\| @[A-Za-z][A-Za-z0-9_-]{0,19}(?![A-Za-z0-9_-])(?!:))|(@[A-Za-z][A-Za-z0-9_-]{0,19}(?![A-Za-z0-9_-]))|(http:\/\/url\.cn\/[A-Za-z0-9]{6}\b)/";
    /**
     * 包含email的匹配
     */
    const REPLACE_PATTERN_INC_EMAIL = "/(#\s*[^#\s]{1}[^#]{0,59}?\s*#)|(\|\| @[A-Za-z][A-Za-z0-9_-]{0,19}(?![A-Za-z0-9_-])(?!:))|(@[A-Za-z][A-Za-z0-9_-]{0,19}(?![A-Za-z0-9_-]))|(http:\/\/url\.cn\/[A-Za-z0-9]{6}\b)|(\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.(?:com|org|net|gov|mil|biz|info|name|aero|biz|info|mobi|jobs|museum|[A-Za-z]{2})\b)|(\/[^\/@#]{2,9}http:\/\/url\.cn\/[A-Za-z0-9]{6}\b)|(\/[^\/@#]{2,9})/";
    /**
     * 短url正则
     */
    const SHORT_URL_PATTERN = "/http:\/\/url\.cn\/([A-Za-z0-9]{6})\b/";
    /**
     * 帐号匹配正则
     */
    const ACCOUNT_PATTERN = "/(@[A-Za-z][A-Za-z0-9_-]{0,19}(?![A-Za-z0-9_-]))/";
    /**
     * 昵称匹配正则
     */
    const BKNAME_PATTERN = "/(@[\x{4e00}-\x{9fa5}A-Za-z0-9_-]{0,12}(?![\x{4e00}-\x{9fa5}A-Za-z0-9_-]))/u";
    /**
     * 获取空回的第一个帐号
     * */
    const EMPTY_REPLAY_TOACCOUNT_PATTERN = "/^@[A-Za-z][A-Za-z0-9_-]{0,19}(?![A-Za-z0-9_-])/";
    /**
     * 消息中url正则
     * */
    const URL_PATTERN = '/((news|telnet|nttp|file|http|ftp|https):\/\/)?(([-A-Za-z0-9]+(\.[-A-Za-z0-9]+)*(\.[-A-Za-z]{2,5}))|([0-9]{1,3}(\.[0-9]{1,3}){3}))(:[0-9]*)?(\/[-A-Za-z0-9_\$\.\+\!\*\(\),;:@&=\?\/~\#\%]*)*/';

    private $replaceData;
    private $isTraditional;
    private $cityConfig;
    private $isLabsUser;
    private $isSimpleView;
    private $videos;
    private $musics;
    private $gb;
    /**
     * 表情替换配置信息
     * @var array
     */
    private $faceReaplceConfigArray;
    /**
     * 是否替换表情
     * @var boolean
     */
    private $faceEnable;

    function __construct($replaceData)
    {
        $this->replaceData = $replaceData;
        $this->isSimpleView = false;
        $this->isLabsUser = false;
        $this->isTraditional = false;
        $this->setFaceEnable(false);
    }

    public function setIsSimpleView($isSimpleView)
    {
        //$this->isSimpleView = $isSimpleView;
        //todo:这里帐号显示版本统一不简约化，版本稳定后删除
        $this->isSimpleView = false;
    }

    function setIsLabsUser($isLabsUser)
    {
        //labs 对外发布
        $this->isLabsUser = $isLabsUser;
    }

    function setVideoViewInfo($videos)
    {
        //设定视频信息
        $this->videos = $videos;
    }

    function setMusicViewInfo($musics)
    {
        //设定音乐信息
        $this->musics = $musics;
    }

    function setShortUrlInfo($message)
    {
        $this->setVideoViewInfo($message['videos']);
        $this->setMusicViewInfo($message['music']);
    }

    /**
     * 启用表情
     * @return boolean
     */
    public function getFaceEnable()
    {
        return $this->faceEnable;
    }

    /**
     * 启用表情
     * @param boolean $faceEnable
     */
    public function setFaceEnable($faceEnable)
    {
        $this->faceEnable = $faceEnable;
        if ($this->faceEnable && empty($this->faceReaplceConfigArray))
        {
            $this->faceReaplceConfigArray = $this->loadFaceConfig();
        }
    }

    /**
     * load表情配置文件
     * @return <type> 
     */
    private function loadFaceConfig()
    {
        require WB_CONFIG_DIR . '/face.config.php';
        $faceReaplceConfigArray = array();
        $searchArray = array();
        $replaceArray = array();
        foreach ($faceConfig as $value)
        {
            $keys = $value['keys'];
            $title = htmlspecialchars($value['title']);
            $url = htmlspecialchars($value['url']);
            foreach ($keys as $k)
            {
                $searchArray[] = htmlspecialchars($k);
                $replaceArray[] = "<img class='crs dn' crs='{$url}' title='{$title}'>";
            }
        }
        $faceReaplceConfigArray['search'] = $searchArray;
        $faceReaplceConfigArray['replace'] = $replaceArray;
        return $faceReaplceConfigArray;
    }

    /**
     * 替换 @ericcao 形式
     * @param string $match
     * @return string
     */
    private function replace_account($match)
    {
        $account = substr($match, 1);
        if (!empty($this->replaceData['account'][strtolower($account)]))
        {
            $nickname = htmlspecialchars($this->replaceData['account'][strtolower($account)]['nick']);
            $accountEscape = htmlspecialchars($account);
            $bkname = $this->replaceData['account'][strtolower($account)]['bkname'];
            $accountInfo = $this->replaceData['account'][strtolower($account)];
            //$accountInfo = array('name'=>$accountEscape, 'nick'=>$nickname, 'bkname'=>$bkname);
            $title = StrFormat::userFullName($accountInfo);
            $convertedAccount = StrFormat::userName($account);
            $nick = (!empty($bkname)) ? $bkname : $nickname;
            if (!$this->isSimpleView)
            {
                return '<em rel="@' . $convertedAccount . '"><a href="/' . $accountEscape . '" title="' . $title . '">' . $nick . '</a>(@' . $convertedAccount . ')</em>';
            }
            else
            {
                return '<em rel="@' . $convertedAccount . '"><a href="/' . $accountEscape . '" title="' . $title . '">' . $nick . '</a></em>';
            }
        }
        return $match;
    }

    /**
     * 替换 http://url.cn/abcdef 形式
     * @param string $match
     * @return string
     */
    private function replace_url($match)
    {
        $shortUrl = $match;
        $shortUrlCode = substr($shortUrl, strlen('http://url.cn/'));

        //显示视频链接
        if (!empty($this->videos[$shortUrlCode]))
        {
            $realUrl = htmlspecialchars(rawurlencode($this->videos[$shortUrlCode]['realUrl']));
            $playerUrl = htmlspecialchars(rawurlencode($this->videos[$shortUrlCode]['playerUrl']));
            $title = htmlspecialchars(trim($this->videos[$shortUrlCode]['title']));
            $miniPicUrl = htmlspecialchars($this->videos[$shortUrlCode]['miniPicUrl']);

            return "<a target=\"_blank\" href=\"{$shortUrl}\" class=\"ico_video\" shorturl=\"{$shortUrlCode}\"  reltitle=\"{$title}\">{$shortUrl}</a>";
        }

        //显示音乐链接
        if (!empty($this->musics[$shortUrlCode]))
        {
            $sMusicName = htmlspecialchars(rawurlencode($this->musics[$shortUrlCode]['sMusicName']));
            $sMusicAuthor = htmlspecialchars(rawurlencode($this->musics[$shortUrlCode]['sMusicAuthor']));
            $title = trim($sMusicName . '-' . $sMusicAuthor);

            return "<a target=\"_blank\" href=\"{$shortUrl}\" class=\"ico_music\" shorturl=\"{$shortUrlCode}\"  reltitle=\"{$title}\">{$shortUrl}</a>";
        }

        return "<a href=\"{$shortUrl}\" class=\"url\" target=\"_blank\">{$shortUrl}</a>";
    }

    /**
     * 替换 ||@ericcao 形式  为带:号形式
     * @param string $match
     * @return string
     */
    private function replace_rt_account($match)
    {
        $account = substr($match, 4);
        if (!empty($this->replaceData['account'][strtolower($account)]))
        {
            $nickname = htmlspecialchars($this->replaceData['account'][strtolower($account)]['nick']);
            $accountEscape = htmlspecialchars($account);
            $nick = (!empty($bkname)) ? $bkname : $nickname;
            $title = $nick . "(@{$accountEscape})";
            if (true)
            {
                if (!$this->isSimpleView)
                {
                    return '|| <em rel="@' . $accountEscape . '"><a href="/' . $accountEscape . '" title="' . $title . '">' . $nick . '</a>(@' . $accountEscape . ')</em>: ';
                }
                else
                {
                    return '|| <em rel="@' . $accountEscape . '"><a href="/' . $accountEscape . '" title="' . $title . '">' . $nick . '</a></em>: ';
                }
            }
            else
            {
                return '|| <em rel="@' . $accountEscape . '"><a href="/' . $accountEscape . '" title="' . $title . '">' . $nick . '</a></em>';
            }
        }
        return $match;
    }

    public function bkNameFormat($content)
    {
        return preg_replace_callback(self::BKNAME_PATTERN, array($this, "replace_bkname_callback"), $content);
    }

    private function replace_bkname_callback($matches)
    {
        $match = $matches[0];
        if ($match[0] == '@')
        {
            $bkname = substr($match, 1);
            if (isset($this->replaceData['bkname'][$bkname]))
            {
                return '@'.$this->replaceData['bkname'][$bkname];
            }
        }
        return $match;
    }

    private function replace_callback($matches)
    {
        $match = $matches[0];
        if ($match[0] == '@')
        {
            return $this->replace_account($match);
        }
        elseif (substr($match, 0, 2) == '||')
        {
            return $this->replace_rt_account($match);
        }
        elseif ($match[0] == '#')
        {
            //话题
            $subject = htmlspecialchars_decode(trim(substr($match, 1, -1)));
            $subject = trim(StrUtil::trim($subject, "　"));
            //这里单独过滤掉"." url路径问题mb_strlen($str,'UTF-8'); 

            if (strlen($subject) == 0 || $subject == "." || mb_strlen($subject, 'UTF-8') > 20)
            {
                return $match;
            }
            $key = self::keywordencode($subject);
            return '<a href="/k/' . $key . '">#' . htmlspecialchars($subject) . '#</a>';
        }
        elseif (substr($match, 0, 4) == 'http')
        {
            //短地址
            //$shortUrl = $match;
            //return "<a href=\"{$shortUrl}\" target=\"_blank\">{$shortUrl}</a>";
            return $this->replace_url($match);
        }
        elseif (!empty($matches[5]))
        {
            $mail = self::keywordencode($matches[5]);
            return '<a href="mailto:' . $mail . '" title="' . htmlspecialchars($matches[5]) . '">' . htmlspecialchars($matches[5]) . '</a>';
        }
        elseif(!empty($matches[6]))
        {
            //替换 /表情http://url.cn/XXX
            $index = strpos($matches[6], "http");
            $faceStr = substr($matches[6], 0, $index);
            $urlStr = substr($matches[6], $index);
            if ($this->faceEnable)
            {
                $face = str_replace($this->faceReaplceConfigArray['search'], $this->faceReaplceConfigArray['replace'], $faceStr);
            }
            else
            {
                $face = $faceStr;
            }
            $url = $this->replace_url($urlStr);
            return $face . $url;
        }elseif($this->faceEnable && !empty($matches[7]))
        {
            //替换表情
            return str_replace($this->faceReaplceConfigArray['search'], $this->faceReaplceConfigArray['replace'], $matches[7]);
        }
        return $match;
    }

    private function replace_callback_outweb($matches)
    {
        $match = $matches[0];
        if ($match[0] == '@')
        {
            //帐号
            $account = substr($match, 1);
            if (!empty($this->replaceData['account'][strtolower($account)]))
            {
                $nickname = htmlspecialchars($this->replaceData['account'][strtolower($account)]['nick']);
                $bkname = $this->replaceData['account'][strtolower($account)]['bkname'];
                $accountEscape = htmlspecialchars($account);
                $accountInfo = $this->replaceData['account'][strtolower($account)];
                //$accountInfo = array('name'=>$accountEscape, 'nick'=>$nickname, 'bkname'=>$bkname);
                $title = StrFormat::userFullName($accountInfo);
                $convertedAccount = StrFormat::userName($account);

                $title = $nickname . "(@{$accountEscape})";

                if (!$this->isSimpleView)
                {
                    return '<em rel="@'. $convertedAccount. '"><a target="_blank" href="http://t.qq.com/' . $accountEscape . '" title="' . $title . '">' . $nickname . '</a>(@' . $convertedAccount . ')</em>';
                }
                else
                {
                    return '<em rel="@'. $convertedAccount. '"><a target="_blank" href="http://t.qq.com/' . $accountEscape . '" title="' . $title . '">' . $nickname . '</a></em>';
                }

            }
            return $match;
        }
        elseif ($match[0] == '#')
        {
            //话题
            $subject = htmlspecialchars_decode(trim(substr($match, 1, -1)));
            $subject = trim(StrUtil::trim($subject, "　"));
            if (strlen($subject) == 0 || $subject == "." || mb_strlen($subject, 'UTF-8') > 20)
            {
                return $match;
            }
            $key = self::keywordencode($subject);
            return '<a target="_blank" href="http://t.qq.com/k/' . $key . '">#' . htmlspecialchars($subject) . '#</a>';
        }
        elseif (substr($match, 0, 4) == 'http')
        {
            //短地址
            $shortUrl = $match;
            return "<a href=\"{$shortUrl}\" target=\"_blank\">{$shortUrl}</a>";
        }
        return $match;
    }

    private function replace_callback_nick($matches)
    {
        $match = $matches[0];
        if ($match[0] == '@')
        {
            //帐号
            $account = substr($match, 1);
            if (!empty($this->replaceData['account'][strtolower($account)]))
            {
                $accountInfo = $this->replaceData['account'][strtolower($account)];
                $nickname = $this->replaceData['account'][strtolower($account)]['nick'];
                $accountEscape = htmlspecialchars($account);
                //$accountInfo['name'] = $accountEscape;
                if (true)
                {
                    if (!$this->isSimpleVie)
                    {
                        return StrFormat::userFullName($accountInfo);
                        //return htmlspecialchars($nickname) . '(@' . $accountEscape . ')';
                    }
                    else
                    {
                        return htmlspecialchars($nickname) . '';
                    }
                }
                else
                {
                    return htmlspecialchars($nickname);
                }
            }
            return $match;
        }
        elseif (substr($match, 0, 2) == '||')
        {
            $account = substr($match, 4);
            if (!empty($this->replaceData['account'][strtolower($account)]))
            {
                $accountInfo = $this->replaceData['account'][strtolower($account)];
                $nickname = $this->replaceData['account'][strtolower($account)]['nick'];
                $bkname = $this->replaceData['account'][strtolower($account)]['bkname'];
                $accountEscape = htmlspecialchars($account);
//                $accountInfo['name'] = $accountEscape;
//                $accountInfo = array('nick'=>$nickname, 'name'=>$accountEscape, 'bkname'=>$bkname);
                if (true)
                {
                    if ($this->isSimpleView)
                    {
                        return StrFormat::userFullName($accountInfo);
                        //return "|| " . htmlspecialchars($nickname) . '(@' . $accountEscape . '): ';
                    }
                    else
                    {
                        return "|| " . htmlspecialchars($nickname) . ': ';
                    }
                }
                else
                {
                    return htmlspecialchars($nickname);
                }
            }
            return $match;
        }
        return $match;
    }

    /**
     * 格式化消息:帐号,url,话题
     * @param string $content  消息内容
     * @return string
     */
    function format($content)
    {
        if (!is_array($content)) //支持之前的协议，如果不是数组的话，就走之前的协议。默认视频不显示
        {
            $this->setShortUrlInfo(array());
        }
        else
        {
            $this->setShortUrlInfo($content);
            $content = $content['content'];
        }

        $content = htmlspecialchars($content);
        $content = preg_replace_callback(self::REPLACE_PATTERN_INC_EMAIL, array($this, "replace_callback"), $content);
        //搜索结果标红处理
        if (!empty($this->replaceData['redKeyWord']))
        {
            //按照消息解释的规则，只有我们才会输出<>,以此来作为判断的依据吧
            $contentArr = self::divideMessage($content);
            $out = array();
            foreach ($contentArr as $splitContent)
            {
                if (strlen($splitContent) > 0 && $splitContent[0] != '<')
                {
                    $out[] = SearchUtil::highlightKeyWords($splitContent, $this->replaceData['redKeyWord'], false);
                }
                else
                {
                    $out[] = $splitContent;
                }
            }
            $content = implode('', $out);
        }
        $content = $this->simple2Traditional($content);
        return $content;
    }

    public static function existChineseID($msg)
    {
        if (empty($msg))
        {
            return false;
        }
        if (preg_match("/@[A-Za-z0-9_\-]{0,16}[\x{4e00}-\x{9fa5}]/u", $msg))
        {
            return true;
        }
        return false;
    }
    
    function outWebFormat($content)
    {
        if (!is_array($content)) //支持之前的协议，如果不是数组的话，就走之前的协议。默认视频不显示
        {
            $this->setShortUrlInfo(array());
        }
        else
        {
            $this->setShortUrlInfo(array());
            $content = $content['content'];
        }

        $content = htmlspecialchars($content);
        return $this->simple2Traditional(preg_replace_callback(self::REPLACE_PATTERN, array($this, "replace_callback_outweb"), $content));
    }

    /**
     * 格式化消息,只替换帐号
     * @param string $content  消息内容
     * @return string
     */
    function formatNick($content, $escape = false)
    {
        if (is_array($content)) //支持之前的协议，如果不是数组的话，就走之前的协议。默认视频不显示
        {
            $content = $content['content'];
        }

        if ($escape)
        {
            $content = htmlspecialchars($content);
        }
        return $this->simple2Traditional(preg_replace_callback(self::REPLACE_PATTERN, array($this, "replace_callback_nick"), $content));
    }

    /**
     * 格式话并输入消息(帐号,话题，url)
     * @param string $content
     */
    function echoFormat($content)
    {
        echo $this->format($content);
    }

    /**
     * 格式话并输入私信(帐号,话题，url)
     * @param string $content
     */
    function echoFormatDirect($content)
    {
        echo $this->format($content);
    }

    /**
     * 格式话并私信(帐号,话题，url)
     * @param string $content
     */
    function formatDirect($content)
    {
        return $this->format($content);
    }

    function divideMessage($content)
    {
        $result = array();
        $pos = strpos($content, '<');
        while ($pos !== false)
        {
            if ($pos > 0)
            {
                $result[] = substr($content, 0, $pos);
                $content = substr($content, $pos);
            }

            $posEnd = strpos($content, '>');
            if ($posEnd !== false)
            {
                $result[] = substr($content, 0, $posEnd + 1);
                $content = substr($content, $posEnd + 1);
                $pos = strpos($content, '<');
            }
            else
            {
                break;
            }
        }

        $result[] = $content;
        return $result;
    }

    /**
     * 格式话消息中的帐号显示为昵称(对话中使用)
     * @param string $content
     */
    function echoFormatNick($content)
    {
        echo $this->formatNick($content, true);
    }

    function formatLoacation($loacation, $wordOnly = false)
    {
        if (empty($loacation))
        {
            return;
        }
        if (empty($this->cityConfig))
        {
            require WB_CONFIG_DIR . "/city.config.php";
            $this->cityConfig = $cityConfig;
        }

        $nation = $loacation['nation'];
        $province = $loacation['province'];
        $city = $loacation['city'];
        if (empty($this->cityConfig[$nation]))
        {
            return;
        }
        $nationArray = &$this->cityConfig[$nation];
        $loacationNameArray['nation'] = $nationArray['name'];
        if (!empty($nationArray['province'][$province]))
        {
            $loacationNameArray['province'] = $nationArray['province'][$province]['name'];
            $loacationNameArray['city'] = $nationArray['province'][$province]['city'][$city];
        }
        else
        {
            $loacationNameArray['province'] = "";
            $loacationNameArray['city'] = "";
        }

        if ($nation == 1)
        {
            //如果是中国，则直接显示省的id列表
            $showProvinceList = array(
                "11" => 1, //北京
                '31' => 1, //上海
                '50' => 1, //重庆
                '12' => 1, //天津
                '81' => 1, //香港
                '82' => 1, //澳门
                '71' => 1, //台湾
            );
            if (isset($showProvinceList[$province]))
            {
                if ($wordOnly)
                {
                    echo $this->simple2Traditional($loacationNameArray['province']);
                }
                else
                {
                    echo $this->simple2Traditional("<a href='/p/city?s={$province}' class='location'>{$loacationNameArray['province']}</a>");
                }

                return;
            }
            if ($wordOnly)
            {
                echo $this->simple2Traditional($loacationNameArray['city']);
            }
            else
            {
                echo $this->simple2Traditional("<a href='/p/city?s={$province}&c={$city}' class='location'>{$loacationNameArray['city']}</a>");
            }

            return;
        }
        //国外显示国家 modified by hobowo on 2010-6-9
        echo $this->simple2Traditional("<a href='/p/city?n={$nation}' class='location'>{$loacationNameArray['nation']}</a>");
        //echo $loacationNameArray['nation'];
        return;
    }

    function setLoacation($loacation, $wordOnly = false)
    {
        if (empty($loacation))
        {
            return;
        }
        if (empty($this->cityConfig))
        {
            require WB_CONFIG_DIR . "/city.config.php";
            $this->cityConfig = $cityConfig;
        }

        $nation = $loacation['nation'];
        $province = $loacation['province'];
        $city = $loacation['city'];
        if (empty($this->cityConfig[$nation]))
        {
            return;
        }
        $nationArray = &$this->cityConfig[$nation];
        $loacationNameArray['nation'] = $nationArray['name'];
        if (!empty($nationArray['province'][$province]))
        {
            $loacationNameArray['province'] = $nationArray['province'][$province]['name'];
            $loacationNameArray['city'] = $nationArray['province'][$province]['city'][$city];
        }
        else
        {
            $loacationNameArray['province'] = "";
            $loacationNameArray['city'] = "";
        }

        if ($nation == 1)
        {
            //如果是中国，则直接显示省的id列表
            $showProvinceList = array(
                "11" => 1, //北京
                '31' => 1, //上海
                '50' => 1, //重庆
                '12' => 1, //天津
                '81' => 1, //香港
                '82' => 1, //澳门
                '71' => 1, //台湾
            );
            if (isset($showProvinceList[$province]))
            {
                if ($wordOnly)
                {
                    return $this->simple2Traditional($loacationNameArray['province']);
                }
                else
                {
                    return $this->simple2Traditional("<a href='/p/city?s={$province}' class='location'>{$loacationNameArray['province']}</a>");
                }

                return;
            }
            if ($wordOnly)
            {
                return $this->simple2Traditional($loacationNameArray['city']);
            }
            else
            {
                return $this->simple2Traditional("<a href='/p/city?s={$province}&c={$city}' class='location'>{$loacationNameArray['city']}</a>");
            }

            return;
        }
        //国外显示国家 modified by hobowo on 2010-6-9
        return $this->simple2Traditional("<a href='/p/city?n={$nation}' class='location'>{$loacationNameArray['nation']}</a>");
        //echo $loacationNameArray['nation'];
    }

    public function relayFormat($content)
    {
        if (is_array($content)) //支持之前的协议，如果不是数组的话，就走之前的协议。
        {
            $content = $content['content'];
        }

        $this->setShortUrlInfo(array());
//        $pos = stripos($content, "||");
//        if ($pos !== false)
//        {
//            if ($this->isLabsUser)
//            {
//                $pos = stripos($content, "||", $pos + 2);
//                if ($pos !== false)
//                {
//                    $content = substr($content, 0, $pos);
//                }
//            }
//            else
//            {
//                $content = substr($content, 0, $pos);
//            }
//        }
        $content = htmlspecialchars($content);
        $content =  $this->simple2Traditional(preg_replace_callback(self::REPLACE_PATTERN_INC_EMAIL, array($this, "replace_callback"), $content));
        return $content;
    }

    /**
     * 转发消息的格式化(||后面的全部去掉)
     * @param string $content
     */
    public function echoRelayFormat($content)
    {
        echo $this->relayFormat($content);
    }

    /*
     * 设置是否显示繁体
     */

    public function setIsTraditional($t)
    {
        $this->isTraditional = $t;
        if ($this->isTraditional)
        {
            $this->gb = file_get_contents(WB_CONFIG_DIR . "/gbk_zh_CN-zh_TW.table");
        }
    }

    /*
     * GB码转换成Big5码
     */

    public function GbkZhCNtoZhTw($str)
    {
        $beginZhCnArea = 0xB0; //gbk简体开始区
        $endZhCnArea = 0xF7; //gbk简体结束区

        $beginZhCnAreaBit = 0xa0; //gbk简体开始区位码
        $endZhCnAreaBit = 0xff; //gbk简体结束区位码

        $max = strlen($str) - 1;
        for ($i = 0; $i < $max; $i++)
        {
            $h = ord($str[$i]);
            if ($h >= 0x80)
            {
                if ($h >= $beginZhCnArea && $h <= $endZhCnArea)
                {
                    $l = ord($str[$i + 1]);
                    if ($l >= $beginZhCnAreaBit)
                    {
                        //192 = 0x60 * 2
                        $index = ($h - $beginZhCnArea) * 192 + ($l - $beginZhCnAreaBit) * 2;
                        $ch1 = $this->gb[$index];
                        if (ord($ch1) != 0x00)
                        {
                            $ch2 = $this->gb[$index + 1];
                            $str[$i] = $ch1;
                            $str[$i + 1] = $ch2;
                        }
                    }
                }
                $i++;
            }
        }
        return $str;
    }


    /*
     * 简体转繁体
     */

    public function simple2Traditional($str)
    {
        if ($this->isTraditional)
        {
            //替换掉一个特殊字符,不属于gbk的 utf-8(0xC2A0)
            //注意:特殊字符不要修改史特特殊的不是空格
            $str = str_replace(" ", "", $str);
            $str_2 = iconv('UTF-8', 'GBK', $str);
            if ($str_2 == false)
            {
                return $str;
            }
            $str1 = iconv('GBK', 'UTF-8', $this->GbkZhCNtoZhTw($str_2));
            if ($str1 == false)
            {
                return $str;
            }
            return $str1;
        }
        return $str;
    }

    public static function keywordencode($key)
    {
        return rawurlencode(str_replace(array('/', '?', '&', '#'), array('%2F', '%3F', '%26', '%23'), $key));
    }

    /**
     * 获取空回消息的空回对象
     * @param array $message 消息内容
     * @return boolean | array account 如果false 则认为空回不合法
     */
    public function getEmptyReplayAccount(&$message)
    {
        $matches = array();
        if (preg_match(self::EMPTY_REPLAY_TOACCOUNT_PATTERN, $message['content'], $matches))
        {
            $name = substr($matches[0], 1); //去掉@
            if (!empty($this->replaceData['account'][$name]))
            {
                return $this->replaceData['account'][$name];
            }
        }
        return false;
    }

    /**
     * 输出空回消息，第一个合法帐号不显示
     * @param array $message
     */
    public function echoFormatEmptyReplay(&$message)
    {
        echo $this->formatEmptyReplay($message);
    }

    /**
     * 返回空回消息，第一个合法帐号不显示
     * @param array $message
     * @return string 格式化后的消息内容
     */
    public function formatEmptyReplay(&$message)
    {
        $content = $message['content'];
        if (preg_match(self::EMPTY_REPLAY_TOACCOUNT_PATTERN, $message['content'], $matches))
        {
            $name = substr($matches[0], 1); //去掉@
            if (!empty($this->replaceData['account'][$name]))
            {
                $content = substr($content, strlen($name) + 1);
            }
        }
        $message['content'] = $content;
        return $this->format($message);
    }

    /**
     * 判断转播消息是否为空消息(没有点评)
     * @param array $message
     * @return boolean
     */
    public static function isRelayContentEmpty($message)
    {
        return (strlen($message['content']) == 0);
//        $content = ltrim($message['content']);
//        $type = $message['type'];
//        if ((strpos($content, "||") === 0) || ( (strlen($content) == 0) && ($type == 2)))
//        {
//            return true;
//        }
//        else
//        {
//            return false;
//        }
    }
}

